package com.example.test_witns.ui.post_blog;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.example.test_witns.R;
import com.example.test_witns.databinding.ActivityPostBlogBinding;
import com.example.test_witns.pojo.Blog;
import com.example.test_witns.pojo.ProgressDialogFragment;
import com.example.test_witns.pojo.ProgressRequestBody;
import com.example.test_witns.utils.GlideEngine;
import com.example.test_witns.utils.MyInfosHelper;
import com.example.test_witns.utils.OssUtil;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

public class PostBlogActivity extends AppCompatActivity {
    String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    String accessKeyId = "LTAI5tMMT1mKsUbjgvunz56D";
    String accessKeySecret = "BxCzPRF4aTosxFnfrIZzAmLdatjoGV";
    String bucketName = "fftechuseravater";
    private ActivityPostBlogBinding binding;
    private String coverImageURL;
    private Uri coverImageUri;
    private String contentImagesURLs = null;
    private List<Uri> uriList = new ArrayList<>();
    private String contentImagesURL1;
    private String contentImagesURL2;
    private int contentImageNum = 0;
    ProgressBar postBlogProgressBar;
    private LinearLayout llImage_post_blog;
    private DialogFragment progressDialogFragment;
    private TextView post_blog_add_picture;
    private ProgressDialog progressDialog;

    public interface BlogApiService{
        @POST("uploadBlog")
        Call<ResponseBody> uploadBlog(@Body Blog blog);

        @GET("getBlogByID")
        Call<Blog> getBlogByID(@Query("ID") long blog_ID);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPostBlogBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        postBlogProgressBar = findViewById(R.id.postBlogProgressBar);
        progressDialogFragment = new ProgressDialogFragment();

        Objects.requireNonNull(getSupportActionBar()).hide();
        Window window = getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        window.setStatusBarColor(Color.parseColor("#eeeeee"));

        View post_blog_cancel = findViewById(R.id.post_blog_cancel);
        post_blog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ImageView post_blog_set_cover_ImageView = findViewById(R.id.post_blog_set_cover_ImageView);
        View post_blog_set_cover_TextView = findViewById(R.id.post_blog_set_cover_TextView);
        post_blog_set_cover_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choseAndLoadCoverImage(post_blog_set_cover_ImageView);
                post_blog_set_cover_TextView.setVisibility(View.INVISIBLE);
            }
        });

        llImage_post_blog = findViewById(R.id.llImage_post_blog);
        post_blog_add_picture = findViewById(R.id.post_blog_add_picture);
        post_blog_add_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choseAndLoadContentImages(llImage_post_blog);
            }
        });

        View post_blog_confirm = findViewById(R.id.post_blog_confirm);
        post_blog_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView post_blog_main_title = findViewById(R.id.post_blog_main_title);
                String mainTitle = post_blog_main_title.getText().toString();
                TextView post_blog_subtitle = findViewById(R.id.post_blog_subtitle);
                String subtitle = post_blog_subtitle.getText().toString();
                TextView post_blog_content = findViewById(R.id.post_blog_content);
                String content = post_blog_content.getText().toString();

                MyInfosHelper myInfosHelper = new MyInfosHelper(PostBlogActivity.this);
                String myNickname = myInfosHelper.getMyNickname();
                String myAvatarURL = myInfosHelper.getMyAvatarURL();

                if (!mainTitle.isEmpty()) {
                    if (mainTitle.length() > 3 && mainTitle.length() < 13){
                        if (!subtitle.isEmpty()){
                            if (!content.isEmpty()){
                                if (content.length() < 20000){
                                    runOnUiThread(() -> {
                                        Toast.makeText(PostBlogActivity.this, "正在上传", Toast.LENGTH_SHORT).show();
                                    });
                                    String[] contentImagesURLList = null;
                                    if (contentImagesURLs != null){
                                        contentImagesURLList = contentImagesURLs.split(",");
                                    }
                                    uploadBlog(myNickname, myAvatarURL, coverImageURL, contentImagesURLs, mainTitle, subtitle, content);
                                    if (coverImageURL != null) UploadCoverImage(coverImageURL, coverImageUri);
                                    short imageCounter = 0;
                                    if (!uriList.isEmpty()){
                                        for (Uri uri :
                                                uriList) {
                                            uploadImageToOSS(bucketName, "images/blogContentImages/" + contentImagesURLList[imageCounter++], null, uri);
                                        }
                                    }
                                    finish();
                                }else {
                                    Toast.makeText(PostBlogActivity.this, "正文不能超过2w字", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                Toast.makeText(PostBlogActivity.this, "正文不能为空", Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            Toast.makeText(PostBlogActivity.this, "副标题不能为空", Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        Toast.makeText(PostBlogActivity.this, "标题字数在4到12之间", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(PostBlogActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void uploadBlog(String owner, String owner_AvatarURL, String cover_Image_URL, String content_Images_URL, String main_title, String subtitle, String content) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + "101.35.251.218" + ":8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        BlogApiService service = retrofit.create(BlogApiService.class);
        Blog blog = new Blog(0L, owner, owner_AvatarURL, cover_Image_URL, null,
                content_Images_URL, main_title, subtitle, content, 0, 0, 0, null);

        // 创建自定义的 ProgressRequestBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(blog));
        ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, new ProgressRequestBody.ProgressListener() {
            @Override
            public void onProgress(long bytesWritten, long contentLength) {
                final int progress = (int) ((bytesWritten * 100) / contentLength);
                runOnUiThread(() -> {
                    postBlogProgressBar.setVisibility(View.VISIBLE);
                    // 更新进度条
                    postBlogProgressBar.setProgress(progress);
                    if (progress == 100) {
                        postBlogProgressBar.setVisibility(View.GONE);
                    }
                });
            }
        });

        Call<ResponseBody> call = service.uploadBlog(blog);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(PostBlogActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                    });
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(PostBlogActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    });
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                runOnUiThread(() -> {
                    Toast.makeText(PostBlogActivity.this, "失败啦,请检查网络", Toast.LENGTH_SHORT).show();
                });
            }
        });

        // 显示进度条
        postBlogProgressBar.setVisibility(View.VISIBLE);
    }

    public Blog getBlogByID(long blog_ID){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://" + R.string.backend_Service_IP + ":8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        BlogApiService service = retrofit.create(BlogApiService.class);
        Call<Blog> call = service.getBlogByID(blog_ID);
        call.enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<Blog> call, Response<Blog> response) {
                if (response.isSuccessful()){
                    Toast.makeText(PostBlogActivity.this, "获取成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(PostBlogActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Blog> call, Throwable t) {
                Toast.makeText(PostBlogActivity.this, "失败啦,请检查网络", Toast.LENGTH_SHORT).show();
            }
        });
        return null;
    }

    public void UploadContentImages(List<String> contentImageURLList){
        uploadImagesListToOSS(bucketName, contentImageURLList,null, null);
    }

    public void UploadCoverImage(String CoverImageURL, Uri imageUri){
        uploadImageToOSS("fftechuseravater", "images/blogCoverImages/" + coverImageURL, null, imageUri);
    }

    public void choseAndLoadContentImages(LinearLayout llImage){
        PictureSelector.create(PostBlogActivity.this)
                .openGallery(SelectMimeType.ofImage()) // 只打开图片选择
                .setMaxSelectNum(5)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if (!result.isEmpty()) {
                            LocalMedia media = result.get(0);
                            if (media != null){
                                ContentResolver contentResolver = PostBlogActivity.this.getContentResolver();
                                Uri imageUri = Uri.parse(media.getPath());
                                MyInfosHelper myInfosHelper = new MyInfosHelper(PostBlogActivity.this);
                                String my_email = myInfosHelper.getMyUserId();
                                if (imageUri != null) {
                                    if(addAndCheckIfImagesNumOutOfBound(5)) return;
                                    addImageView(imageUri);

                                    contentImagesURLs += (my_email + "contentImage" +UUID.randomUUID().toString() + ".jpg,");
                                    uriList.add(imageUri);
                                }
                                if (result.size() > 1){
                                    if(addAndCheckIfImagesNumOutOfBound(5)) return;
                                    LocalMedia media2 = result.get(1);
                                    Uri imageUri2 = Uri.parse(media2.getPath());
                                    addImageView(imageUri2);

                                    contentImagesURLs += my_email + "contentImage" +UUID.randomUUID().toString() + ".jpg,";
                                    uriList.add(imageUri2);
                                }
                                for (int i = 2; i < result.size(); i++) {
                                    if(addAndCheckIfImagesNumOutOfBound(5)) return;
                                    LocalMedia ex_media = result.get(i);
                                    Uri ex_imageUri = Uri.parse(ex_media.getPath());
                                    addImageView(ex_imageUri);
                                    contentImagesURLs += my_email + "contentImage" +UUID.randomUUID().toString() + ".jpg,";
                                    uriList.add(ex_imageUri);
                                }
                            }
                            String currentImageNum = "+" + uriList.size();
                            post_blog_add_picture.setText(currentImageNum);
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });

    }

    private void addImageView(Uri uri) {
        View view = getLayoutInflater().inflate(R.layout.item_image, llImage_post_blog, false);
        ImageView imageView = view.findViewById(R.id.imageView);
        imageView.setImageURI(uri);

        llImage_post_blog.addView(view);
    }

    public void choseAndLoadCoverImage(ImageView loader){
        // 启动图片选择器，设置为单选模式
        PictureSelector.create(PostBlogActivity.this)
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(1)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if (!result.isEmpty()) {
                            LocalMedia media = result.get(0);
                            if (media != null){
                                ContentResolver contentResolver = PostBlogActivity.this.getContentResolver();
                                Uri imageUri = Uri.parse(media.getPath());
                                if (imageUri != null) {
                                    loader.setImageURI(imageUri);

                                    MyInfosHelper myInfosHelper = new MyInfosHelper(PostBlogActivity.this);
                                    String my_email = myInfosHelper.getMyUserId();
                                    coverImageURL = my_email + "blogCover" +UUID.randomUUID().toString() + ".jpg";
                                    coverImageUri = imageUri;
                                }
                            }
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    public void uploadImageToOSS(String bucketName, String objectName, byte[] imageBytes, Uri uri) {
        OSS ossClient = OssUtil.initOSS(PostBlogActivity.this, endpoint, accessKeyId, accessKeySecret, bucketName);
        try {
            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, uri);
            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 打印结果
            if (result != null) {

            } else {
                System.out.println("Upload Failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    public void addImagesToListByOptional(int minBound, int maxBound, ArrayList<LocalMedia> result){
        for (int i = minBound; i < maxBound; i++){
            Optional<LocalMedia> media2 = Optional.ofNullable(result.get(i));
            media2.ifPresent(new Consumer<LocalMedia>() {
                @Override
                public void accept(LocalMedia media) {
                    ContentResolver contentResolver = PostBlogActivity.this.getContentResolver();
                    Uri imageUri = Uri.parse(media.getPath());
                    if (imageUri != null) {
                        MyInfosHelper myInfosHelper = new MyInfosHelper(PostBlogActivity.this);
                        String my_email = myInfosHelper.getMyUserId();
                        contentImagesURLs += my_email + "contentImage" +UUID.randomUUID().toString() + ".jpg,";
                    }
                }
            });
        }
    }

    public void uploadImagesListToOSS(String bucketName, List<String> objectNameList, byte[] imageBytes, Uri uri){
        for (int i = 0; i < objectNameList.size(); i++){
            OSS ossClient = OssUtil.initOSS(PostBlogActivity.this, endpoint, accessKeyId, accessKeySecret, bucketName);
            try {
                // 创建上传请求
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectNameList.get(i), uri);
                // 上传文件
                PutObjectResult result = ossClient.putObject(putObjectRequest);
                // 打印结果
                if (result != null) {

                } else {
                    System.out.println("Upload Failed.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        }
    }

    public boolean addAndCheckIfImagesNumOutOfBound(int bound){
        contentImageNum++;
        if (contentImageNum > bound) {
            Toast.makeText(this, "最多上传" + bound + "张图片", Toast.LENGTH_SHORT).show();
        }return contentImageNum > bound;
    }

}
